import tkinter as tk
import re
import yaml
import time
import datetime


def read_ics_config():  # 读取iCalConfig.yml文件
    try:
        with open('iCalConfig.yml', 'r', encoding='utf-8') as f:
            yml_data = yaml.load(f.read(), Loader=yaml.FullLoader)
        f.close()
        return yml_data
    except:
        print("读取配置文件错误！")
        return "false"


def create_as_ics(title, teacher, date, times, url):
    ics_string = ""
    yml_data = read_ics_config()
    year = datetime.datetime.now().year  # 当前年份                2020
    dates = time.strftime("%m%d", time.strptime(date, "%m月%d日"))  # 把 X年X月 转为 mmdd     0409
    begin_time = times[:times.rfind("-")].replace(":", "")  # 开始时间，无 : 的        1900
    end_time = times[times.rfind("-") + 1:].replace(":", "")  # 结束时间，无 : 的        2000
    begin_datetime = str(year) + dates + "T" + begin_time + "00"  # 20200409T190000
    end_datetime = str(year) + dates + "T" + end_time + "00"  # 20200409T200000
    create_datetime = time.strftime("%Y%m%dT%H%M%S", time.localtime())  # 20200410T150526
    cur_datetime = create_datetime + "Z"  # 20200410T150526Z
    if "false" != yml_data:
        ics_string = "BEGIN:" + yml_data["BEGIN"]["CAL"] + "\n"
        ics_string = ics_string + "PRODID:" + yml_data["PRODID"]["OUTLOOK"] + "\n"
        ics_string = ics_string + "VERSION:" + str(yml_data["VERSION"]) + "\n"
        ics_string = ics_string + "CALSCALE:" + yml_data["CALSCALE"]["GREGORIAN"] + "\n"
        ics_string = ics_string + "METHOD:" + yml_data["METHOD"]["PUBLISH"] + "\n"
        ics_string = ics_string + "X-WR-CALNAME:" + yml_data["X-WR-CALNAME"] + "\n"
        ics_string = ics_string + "X-WR-TIMEZONE:" + yml_data["X-WR-TIMEZONE"] + "\n"
        ics_string = ics_string + "BEGIN:" + yml_data["BEGIN"]["EVENT"] + "\n"
        ics_string = ics_string + "SUMMARY:" + title + "\n"
        ics_string = ics_string + "DTSTART;TZID=Asia/Shanghai:" + begin_datetime + "\n"
        ics_string = ics_string + "DTEND;TZID=Asia/Shanghai:" + end_datetime + "\n"
        ics_string = ics_string + "DTSTAMP:" + cur_datetime + "\n"
        ics_string = ics_string + "CREATED:" + create_datetime + "\n"
        ics_string = ics_string + "LOCATION:" + "腾讯课堂" + "\n"
        ics_string = ics_string + "DESCRIPTION:" + "讲师：" + teacher + "\\n链接:" + url + "\n"
        ics_string = ics_string + "BEGIN:" + yml_data["BEGIN"]["ALARM"] + "\n"
        ics_string = ics_string + "UID:" + cur_datetime + "&" + yml_data["UID"] + "\n"
        ics_string = ics_string + "TRIGGER:" + yml_data["TRIGGER"]["30M"] + "\n"
        ics_string = ics_string + "END:" + yml_data["END"]["ALARM"] + "\n"
        ics_string = ics_string + "END:" + yml_data["END"]["EVENT"] + "\n"
        ics_string = ics_string + "END:" + yml_data["END"]["CAL"] + "\n"
    return ics_string


def save_as_ics(string, title):  #保存为ics文件
    with open(title + ".ics", 'wb') as f:
        f.write(string.encode("utf-8"))
        f.close()


def ics_create_and_save(title, teacher, date, times, url):
    ics_string = create_as_ics(title, teacher, date, times, url)
    if "" != ics_string:
        save_as_ics(ics_string, title)


def exec_calendar(title):
    try:
        fp = open(title + ".ics", "r")
        print("文件打开")
    except IOError:
        print("文件打开错误")


def create_to_calendar_and_exec():
    # 获取文本框内容
    text_string = text.get("0.0", "end")  # 第一个参数"0.0"是指从第0行第0列开始读取，第二个参数End表示最后一个字符
    text_list = text_string.split()
    title = ""
    teacher = ""
    date = ""
    times = ""
    url = ""
    reg = "\\d{1,2}[:]\\d{1,2}[-]\\d{1,2}[:]\\d{1,2}"
    for i in range(len(text_list)):
        if ("内容" in text_list[i]) | ("课程" in text_list[i]):
            title = text_list[i][text_list[i].find("：") + 1:]  # 获取冒号后的文字
            print(title)
        if "讲师" in text_list[i]:
            teacher = text_list[i][text_list[i].find("：") + 1:]
            print(teacher)
        if ("时间" in text_list[i]) & ("" == date):
            date = text_list[i][text_list[i].find("：") + 1:]
            print(date)
        s1 = re.findall(reg, text_list[i])
        if len(s1):
            times = s1[0]
            print(times)
        if "链接" in text_list[i]:
            url = text_list[i][text_list[i].find("：") + 1:]
            print(url)
    ics_create_and_save(title, teacher, date, times, url)
    # time.sleep(10)
    exec_calendar(title)


window = tk.Tk()
window.title("工具集")

screenwidth = window.winfo_screenwidth()  # 获取显示器屏幕的宽度
screenheight = window.winfo_screenheight()  # 获取显示器屏幕的高度
width = 800  # 自己设定的窗口宽度
height = 600  # 自己设定的窗口高度

x = (screenwidth - width) / 2  # 中心点x轴
y = (screenheight - height) / 2  # 中心点y轴

window.geometry("%dx%d+%d+%d" % (width, height, x, y))

# entry = tk.Entry(window, show=None)
text = tk.Text(window, undo=True)   # 自定义width=100, height=10,
text.pack(fill="x")         # x轴填充满
button1 = tk.Button(window, text="生成日历文件", command=create_to_calendar_and_exec)
button1.pack()
# button2 = tk.Button(window, text="运行日历文件", command=add_to_calendar)
# button2.pack()
# entry = tk.Entry(window, show=None)
# entry.pack()

window.mainloop()
